package com.example.wx.dailyreport.customtool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.type.TypeReference;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class JWTTool {
    public static final String SECRET = "bq3C;A6C^l<=dH,m3@]@2Cfy0w4v:w4q6w<?.?5F]D8=/n3t6wd?`p8@c<`w8s5D";
    public static final long TIME = 40 * 60 * 1000;
    public static final long MINTIME = 20 * 60 * 1000;
    public static final String NAME = "-";
    public static final String JWT_USERNAME = "un";
    public static final String JWT_ROLE = "rl";
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    public static String createJwt(Map<String, Object> map) {
        long time = System.currentTimeMillis();
        Date iatDate = new Date(time);
        Date expDate = new Date(time + TIME);
        return JWT.create()
                .withClaim(NAME, JsonTool.toJson(map))
                .withIssuedAt(iatDate)
                .withExpiresAt(expDate)
                .sign(Algorithm.HMAC256(SECRET));
    }

    public static Map<String, Object> getMapByJwt(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            return JsonTool.toCollection(jwt.getClaims().get(NAME).asString(), new TypeReference<LinkedHashMap<String, Object>>() {
            });
        } catch (Exception e) {
            return null;
        }
    }

    public static long getExpiresDateByJwt(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getExpiresAt().getTime();
        } catch (Exception e) {
            return -1;
        }
    }

}
